import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Button, message, Spin, Empty } from 'antd';
import { Team } from '@/types/account';
import { accountService } from '@/services/accountService';
import { useTeamStore } from '@/store/useTeamStore';

interface JoinTeamModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const JoinTeamModal: React.FC<JoinTeamModalProps> = ({
  visible,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(false);
  const [joining, setJoining] = useState(false);
  const { setCurrentTeam } = useTeamStore();

  // 获取可用团队列表
  useEffect(() => {
    if (visible) {
      fetchTeams();
    }
  }, [visible]);

  const fetchTeams = async () => {
    setLoading(true);
    try {
      const response = await accountService.getTeams();
      if (response.data && response.data.results) {
        setTeams(response.data.results);
      }
    } catch (error) {
      console.error('获取团队列表失败:', error);
      message.error('获取团队列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleJoinTeam = async (values: { team_id: number; password: string }) => {
    setJoining(true);
    try {
      await accountService.joinTeam(values.team_id, { 
        team_id: values.team_id,
        password: values.password 
      });
      message.success('成功加入团队！');
      
      // 设置当前团队
      const selectedTeam = teams.find(team => team.id === values.team_id);
      if (selectedTeam) {
        setCurrentTeam(selectedTeam);
      }
      
      form.resetFields();
      onSuccess();
    } catch (error: any) {
      console.error('加入团队失败:', error);
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('加入团队失败，请检查密码是否正确');
      }
    } finally {
      setJoining(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title="加入团队"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={500}
    >
      <Spin spinning={loading}>
        {teams.length === 0 ? (
          <Empty description="暂无可加入的团队" />
        ) : (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleJoinTeam}
          >
            <Form.Item
              name="team_id"
              label="选择团队"
              rules={[{ required: true, message: '请选择要加入的团队' }]}
            >
              <Select
                placeholder="请选择团队"
                showSearch
                optionFilterProp="label"
                filterOption={(input, option) => {
                  const teamName = option?.label || '';
                  return teamName.toLowerCase().includes(input.toLowerCase());
                }}
              >
                {teams.map(team => (
                  <Select.Option key={team.id} value={team.id} label={team.name}>
                    <div>
                      <div style={{ fontWeight: 'bold' }}>{team.name}</div>
                      <div style={{ fontSize: '12px', color: '#666' }}>
                        创建者: {team.creator_name} | 成员: {team.member_count}人
                      </div>
                      {team.description && (
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          {team.description}
                        </div>
                      )}
                    </div>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="password"
              label="团队密码"
              rules={[{ required: true, message: '请输入团队密码' }]}
            >
              <Input.Password placeholder="请输入团队密码" />
            </Form.Item>

            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
                <Button onClick={handleCancel}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit" loading={joining}>
                  加入团队
                </Button>
              </div>
            </Form.Item>
          </Form>
        )}
      </Spin>
    </Modal>
  );
};

export default JoinTeamModal; 